/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014 @ ShenZhen ,China
*******************************************************************************/
#ifdef OS_NONUNIX
#else
#include "BaseType.h"
#include "TraceDebug.h"
#include "KeyInput.h"

KeyInput::KeyInput():
m_fdInput(-1)
{
}

KeyInput::~KeyInput()
{
}

bool KeyInput::open(const string& devName)
{
    if (m_fdInput>0)
    {
        return true;
    }
    m_fdInput = ::open(devName.c_str(),O_RDWR);
    if (m_fdInput<0)
    {
        return false;
    }
    m_mainThread.start(this);
    return true;
}

bool KeyInput::close()
{
    if (m_fdInput>0)
    {
        ::close(m_fdInput);
        m_fdInput = -1;
    }
    m_mainThread.cancel();
    m_listenerList.clear();
}
void KeyInput::addKeyListener(KeyListener* listener)
{
    AutoLock lock(&m_listLock);
    m_listenerList.push_back(listener);
}

void KeyInput::delKeyListener(KeyListener* listener)
{
    AutoLock lock(&m_listLock);
    m_listenerList.remove(listener);   
}

void KeyInput::run()
{   
    while(1)
    {
        struct input_event event;
        if((m_fdInput>0) && (read(m_fdInput,&event,sizeof(event))))
        {
            if(event.type != EV_KEY)
		    {
		        continue;
            }
           	if (event.value == 1)
            {
                int keycode=event.code;
                list<KeyListener*>::iterator iter;
                AutoLock lock(&m_listLock);
                for(iter=m_listenerList.begin();iter!=m_listenerList.end();iter++)
                {
                    (*iter)->handleKey(keycode);
                }
			}
		}
    }
}
#endif
